﻿
using Microsoft.AspNetCore.Mvc;
using Sykj.Infrastructure;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;

namespace Sykj.Components
{
    /// <summary>
    /// API基类
    /// </summary>
    [Produces("application/json")]
    [Route("api/v1/[controller]")]
    public class ApiController : BaseController
    {
        private int _userid = 0;

        /// <summary>
        /// 获取登录的用户ID,未登陆返回0
        /// </summary>
        public int UserId
        {
            get
            {
                if (User == null) return _userid;
                if (User.Identity != null)
                {
                    var claim = (User.Identity as ClaimsIdentity).Claims.SingleOrDefault(s => s.Type == JwtRegisteredClaimNames.Jti);
                    if (claim != null)
                        _userid = int.Parse(claim.Value);
                }
                return _userid;
            }
            set { _userid = value; }
        }

        /// <summary>
        /// 根据http头部认证表示，获取userId
        /// </summary>
        public int HeaderUserId
        {
            get
            {
                if (Request == null)
                    return 0;
                var tokenHeader = Request.Headers[Constant.AUTHORIZATION];
                TokenModel tokenModel = JwtHelper.SerializeJWT(tokenHeader.ToString());
                int userId = 0;
                if (tokenModel != null) userId = tokenModel.Uid.ToInt();
                return userId;
            }
        }
    }
}